#include <kernel.h>

struct dde_kit_timer dk_timers[DK_TIMER_COUNT];
static int dkt_proc;

const volatile uint32_t *__LD_jiffies_ptr;
const volatile uint64_t *__LD_jiffies_64_ptr;

struct dde_kit_timer *
LD_SYM(dde_kit_timer_add)(void (*fn)(void *), void *priv,
				  unsigned long timeout)
{
	 struct dde_kit_timer *t = ekf_alloc(sizeof(struct dde_kit_timer));
	 
	 /* dirty hack */
	 unsigned long __timeout = timeout * 10;
	 t->timer = timer_open((timer_cb_f)fn, priv, 1, timer_tick_get() + timer_freq_get() * 0.001 * __timeout);

	 return t;
}

/**
 * Delete timer
 *
 * \param timer  timer reference
 */
void
LD_SYM(dde_kit_timer_del)(struct dde_kit_timer *timer)
{
	 timer_close(timer->timer);
	 ekf_free(timer);
}

/**
 * Check whether a timer is pending
 *
 * \param timer  timer reference
 */
int
LD_SYM(dde_kit_timer_pending)(struct dde_kit_timer *timer)
{
	 return !timer_is_closed(timer->timer);
}

static uint64_t zero = 0;
/** Init timers and ticks */
void
LD_SYM(dde_kit_timer_init)(void(*thread_init)(void *), void *priv)
{
	 __LD_jiffies_ptr    = (const volatile uint32_t *)&zero;
	 __LD_jiffies_64_ptr = (const volatile uint64_t *)&zero;
}

#if DK_EXPORT_SYM

void
dde_kit_timer_symbol(void)
{
	 elf_mod_export_symbol("dde_kit_timer_ticks",   (void *)tick_counter, 1);
	 elf_mod_export_symbol("jiffies",               (void *)&__LD_jiffies, 1);
	 elf_mod_export_symbol("DDE_KIT_HZ",            (void *)&tick_freq, 1);
	 elf_mod_export_symbol("dde_kit_timer_add",     &dde_kit_timer_add, 1);
	 elf_mod_export_symbol("dde_kit_timer_del",     &dde_kit_timer_del, 1);
	 elf_mod_export_symbol("dde_kit_timer_pending", &dde_kit_timer_pending, 1);
	 elf_mod_export_symbol("dde_kit_timer_init",    &dde_kit_timer_init, 1);
}

#endif
